<template>
  <view>
    <view class="money-link" v-if="hasLogin">
      <view @click="jump('/main/Home/childComps/Money/Money')">记一笔</view>
    </view>
    <view class="money-link" style="margin-top: 280rpx" v-else>
      <button class="btn" open-type="chooseAvatar" @chooseavatar="loginX">登陆</button>
    </view>
  </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { httpPOST } from '@/common/req'
export default {

  computed: {
    ...mapState(['hasLogin'])
  },
  methods: {
    ...mapMutations(['login', 'bookRecord', 'todayRecord']),
    jump(url) {
      uni.navigateTo({ url })
    },
    loginX(e) {
      const that = this
      const { avatarUrl } = e.detail
      wx.login({
        async success(res) {
          if (res.code) {
            const appId = wx.getAccountInfoSync().miniProgram.appId
            const s = await that.uploadImg(avatarUrl)
            const url = 'https://api.benlv.top/auth/loginV2'
            const param = {
              js_code: res.code,
              appId
            }
            if (s.url) {
              param.avatarUrl = s.url || ''
            }
            const [err, data] = await httpPOST({ url, param })
            if (data && data.token) {
              that.login(data)
              that.$store.commit('fetchRecords')
              that.bookRecord()
              that.todayRecord()
            } else {
              console.log('登录失败！' + 0o111)
            }
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },

    async uploadImg(filePath) {
      const [err, res] = await uni.uploadFile({
        url: 'https://s.benlv.top/_upload',
        filePath,
        name: 'image',
        header: {
          'content-type': 'multipart/form-data'
        }
      })
      if (!err) {
        return JSON.parse(res.data).data
      }
      return ''
    },
    decryptPhoneNumber(e) {
      console.error(e)
      const appId = wx.getAccountInfoSync().miniProgram.appId
      const env = 1
      const a = { code: e.detail, appId }
      console.log(a, env)
    }
  }
}
</script>

<style lang="scss" scoped>
  .btn{
    margin-top: 28px;
    color: white;
    font-weight: 700;
    border: none !important;
    border-radius: 10rpx;
    background-color: $uni-color-btn;
  }
  .ad{
    margin-top: 200rpx;
  }
  .money-link {
    margin: 28px auto 0;
    background-color: $uni-color-btn;
    font-size: 32rpx;
    height: 76rpx;
    width: 280rpx;
    border-radius: 8rpx;
    color: white;
    line-height: 76rpx;
    text-align: center;
  }
</style>
